package com.hknc.btscale;

import androidx.appcompat.app.AppCompatActivity;

import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hknc.btscale.bean.Constants;
import com.hknc.btscale.bean.LoginPost;
import com.hknc.btscale.bean.LoginResponse;
import com.hknc.btscale.utils.ConnectUtils;
import com.hknc.btscale.utils.NetUtils;
import com.hknc.btscale.utils.SPUtils;
import com.hknc.btscale.utils.network.ApiWrapper;
import com.hknc.btscale.utils.network.MyObserver;
import com.hknc.btscale.utils.network.RxHelper;
import com.hknc.btscale.utils.network.exception.ExceptionHandle;

import org.greenrobot.eventbus.EventBus;

import cn.wandersnail.bluetooth.BTManager;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

public class LoginActivity extends AppCompatActivity {
    private static final String TAG = "LoginActivity";
    private EditText marketId, stallNo;
    private Button loginBt;
    private BluetoothDevice mBluetoothDevice;
    private CountDownTimer mCountDownTimer;
    private Gson mGson=new Gson();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
//        if (!NetUtils.ping()) {
//            Intent intent = new Intent(LoginActivity.this, YangcanliActivity.class);
//            mBluetoothDevice = getIntent().getParcelableExtra("device");
//            if (mBluetoothDevice!=null){
//                intent.putExtra("device", mBluetoothDevice);
//            }
//            startActivity(intent);
//            finish();
//        }
        mBluetoothDevice = getIntent().getParcelableExtra("device");
        initView();
        //如果sp有保存过marketId和stallNo，那么直接开启倒计时，倒计时结束直接自动登录
        if (!SPUtils.getInstance(getApplicationContext()).getSP("marketId").isEmpty()) {
            marketId.setText(SPUtils.getInstance(getApplicationContext()).getSP("marketId"));
            stallNo.setText(SPUtils.getInstance(getApplicationContext()).getSP("stallNo"));
            mCountDownTimer = new CountDownTimer(4050, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    Log.e(TAG, "onTick: " + millisUntilFinished);
                }

                @Override
                public void onFinish() {
                    if (ConnectUtils.isNetWorkConnected(LoginActivity.this)) {//如果是联网状态
//                        Toast.makeText(LoginActivity.this, "联网", Toast.LENGTH_SHORT).show();
                        ApiWrapper.getInstance().login(new LoginPost(Integer.parseInt(marketId.getText().toString()), stallNo.getText().toString()))
                                .compose(RxHelper.to_mian())
                                .subscribe(new MyObserver<LoginResponse>() {
                                    @Override
                                    public void onError(ExceptionHandle.ResponseException responseException) {

                                    }

                                    @Override
                                    public void onSubscribe(@NonNull Disposable d) {

                                    }

                                    @Override
                                    public void onNext(@NonNull LoginResponse loginResponse) {
                                        if (loginResponse.getCode() == 200) {
                                            String loginResponseStr=mGson.toJson(loginResponse);
                                            SPUtils.getInstance(getApplicationContext()).putSP("loginResponse",loginResponseStr);
                                            SPUtils.getInstance(getApplicationContext()).putSP("stallId", loginResponse.getData().getStallId() + "");
                                            SPUtils.getInstance(getApplicationContext()).putSP("marketId", marketId.getText().toString());
                                            SPUtils.getInstance(getApplicationContext()).putSP("stallNo", stallNo.getText().toString());
                                            SPUtils.getInstance(getApplicationContext()).putSP("businessLicensePic", loginResponse.getData().getBusinessLicensePic());
                                            SPUtils.getInstance(getApplicationContext()).putSP("circulationLicense", loginResponse.getData().getCirculationLicense());
                                            SPUtils.getInstance(getApplicationContext()).putSP("alipay", loginResponse.getData().getAlipayPic());
                                            SPUtils.getInstance(getApplicationContext()).putSP("wechat", loginResponse.getData().getWechatPic());
                                            SPUtils.getInstance(getApplicationContext()).putSP("name", loginResponse.getData().getMerchantName());
                                            Constants.STALL_ID = String.valueOf(loginResponse.getData().getStallId());
                                            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                                            if (mBluetoothDevice!=null) {
                                                intent.putExtra("device", mBluetoothDevice);

                                            }
                                            intent.putExtra("tanweihao", stallNo.getText().toString());
                                            Constants.sLoginResponse = loginResponse;
                                            startActivity(intent);
                                            finish();
                                        }
                                        Toast.makeText(LoginActivity.this, loginResponse.getMsg(), Toast.LENGTH_SHORT).show();

                                    }

                                    @Override
                                    public void onComplete() {

                                    }
                                });
                    } else {
//                        Toast.makeText(LoginActivity.this, "断网了哦", Toast.LENGTH_SHORT).show();
                    }
                }
            }.start();
        }

        marketId.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (mCountDownTimer != null) {
                    mCountDownTimer.cancel();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        stallNo.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (mCountDownTimer != null) {
                    mCountDownTimer.cancel();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void initView() {
        marketId = findViewById(R.id.marketid_et);
        stallNo = findViewById(R.id.stallno_et);
        loginBt = findViewById(R.id.login_bt);
        //点击登录
        loginBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCountDownTimer != null) {
                    mCountDownTimer.cancel();
                    mCountDownTimer = null;
                }
                if (marketId.getText().toString().isEmpty() || stallNo.getText().toString().isEmpty()) {
                    Toast.makeText(LoginActivity.this, "市场号或摊位号不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                ApiWrapper.getInstance().login(new LoginPost(Integer.parseInt(marketId.getText().toString()), stallNo.getText().toString()))
                        .compose(RxHelper.to_mian())
                        .subscribe(new MyObserver<LoginResponse>() {
                            @Override
                            public void onError(ExceptionHandle.ResponseException responseException) {

                            }

                            @Override
                            public void onSubscribe(@NonNull Disposable d) {

                            }

                            @Override
                            public void onNext(@NonNull LoginResponse loginResponse) {
                                if (loginResponse.getCode() == 200) {
                                    String loginResponseStr=mGson.toJson(loginResponse);
                                    SPUtils.getInstance(getApplicationContext()).putSP("loginResponse",loginResponseStr);
                                    SPUtils.getInstance(getApplicationContext()).putSP("stallId", loginResponse.getData().getStallId() + "");
                                    SPUtils.getInstance(getApplicationContext()).putSP("marketId", marketId.getText().toString());
                                    SPUtils.getInstance(getApplicationContext()).putSP("stallNo", stallNo.getText().toString());
                                    SPUtils.getInstance(getApplicationContext()).putSP("businessLicensePic", loginResponse.getData().getBusinessLicensePic());
                                    SPUtils.getInstance(getApplicationContext()).putSP("circulationLicense", loginResponse.getData().getCirculationLicense());
                                    SPUtils.getInstance(getApplicationContext()).putSP("alipay", loginResponse.getData().getAlipayPic());
                                    SPUtils.getInstance(getApplicationContext()).putSP("wechat", loginResponse.getData().getWechatPic());
                                    SPUtils.getInstance(getApplicationContext()).putSP("name", loginResponse.getData().getMerchantName());
                                    Constants.STALL_ID = String.valueOf(loginResponse.getData().getStallId());
                                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                                    if (mBluetoothDevice!=null){
                                        intent.putExtra("device", mBluetoothDevice);

                                    }
                                    intent.putExtra("tanweihao", stallNo.getText().toString());
                                    Constants.sLoginResponse = loginResponse;
                                    startActivity(intent);
                                    finish();
                                }
                                Toast.makeText(LoginActivity.this, loginResponse.getMsg(), Toast.LENGTH_SHORT).show();

                            }

                            @Override
                            public void onComplete() {

                            }
                        });
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
            mCountDownTimer = null;
        }
    }

//    @Override
//    public void onBackPressed() {
//        super.onBackPressed();
//        BTManager.getInstance().releaseAllConnections();
//        BTManager.getInstance().disconnectAllConnections();
//        BTManager.getInstance().destroy();
//    }
}
